import React, { useState, useEffect } from 'react';
import { 
  AppBar, 
  Toolbar, 
  Typography, 
  Button, 
  Box, 
  Avatar, 
  Menu, 
  MenuItem, 
  IconButton,
  Divider 
} from '@mui/material';
import { Link, useNavigate } from 'react-router-dom';
import { AccountCircle, ExitToApp, Article, AdminPanelSettings, History, Assessment, Gavel } from '@mui/icons-material';
import { tokenStorage, userStorage, logout, isAuthenticated } from '../utils/api';

const Header: React.FC = () => {
  const navigate = useNavigate();
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [user, setUser] = useState<any>(null);
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);

  // 检查登录状态
  useEffect(() => {
    const checkAuthStatus = () => {
      const authenticated = isAuthenticated();
      const userData = userStorage.get();
      
      setIsLoggedIn(authenticated);
      setUser(userData);
      
      console.log('🔐 当前登录状态:', { authenticated, userData });
    };

    // 初始检查
    checkAuthStatus();

    // 监听存储变化（当其他标签页登录/登出时）
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === 'token' || e.key === 'user') {
        checkAuthStatus();
      }
    };

    window.addEventListener('storage', handleStorageChange);
    
    // 定期检查（防止token过期等情况）
    const interval = setInterval(checkAuthStatus, 30000); // 30秒检查一次

    return () => {
      window.removeEventListener('storage', handleStorageChange);
      clearInterval(interval);
    };
  }, []);

  // 处理用户菜单
  const handleMenuOpen = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleMenuClose = () => {
    setAnchorEl(null);
  };

  // 处理登出
  const handleLogout = () => {
    logout();
    setIsLoggedIn(false);
    setUser(null);
    handleMenuClose();
    navigate('/auth/login');
    console.log('👋 用户已登出');
  };

  // 跳转到个人资料
  const handleProfile = () => {
    handleMenuClose();
    navigate('/profile');
  };

  // 跳转到我的内容
  const handleMyContents = () => {
    handleMenuClose();
    navigate('/my-contents');
  };

  // 跳转到内容管理
  const handleContentManagement = () => {
    handleMenuClose();
    navigate('/admin/content-management');
  };

  // 跳转到推荐管理
  const handleRecommendationManagement = () => {
    handleMenuClose();
    navigate('/admin/recommendation-management');
  };

  // 跳转到审核管理
  const handleAdminReview = () => {
    handleMenuClose();
    navigate('/admin/applications');
  };

  // 跳转到日志页面
  const handleLogs = () => {
    navigate('/logs');
  };

  // 检查是否为管理员
  const isAdmin = user && (user.role === 'ADMIN' || user.role === 'SUPERADMIN');
  // 检查是否为超级管理员
  const isSuperAdmin = user && user.role === 'SUPERADMIN';

  return (
    <AppBar position="static">
      <Toolbar>
        <Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
          <Link to="/home" style={{ color: 'inherit', textDecoration: 'none' }}>
            小蓝书
          </Link>
        </Typography>
        
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <Button color="inherit" component={Link} to="/home">
            首页
          </Button>
          <Button color="inherit" component={Link} to="/recommendations">
            推荐
          </Button>
          <Button color="inherit" component={Link} to="/my-contents">
            我的内容
          </Button>
          <Button color="inherit" component={Link} to="/create">
            创建
          </Button>
          {isLoggedIn && (
            <Button color="inherit" onClick={handleLogs}>
              <History sx={{ mr: 0.5 }} />
              日志
            </Button>
          )}
          {/* 审核按钮 - 仅超级管理员可见 */}
          {isSuperAdmin && (
            <Button color="inherit" onClick={handleAdminReview}>
              <Gavel sx={{ mr: 0.5 }} />
              审核
            </Button>
          )}
          
          {isLoggedIn ? (
            // 已登录状态
            <>
              <IconButton
                size="large"
                aria-label="用户菜单"
                aria-controls="user-menu"
                aria-haspopup="true"
                onClick={handleMenuOpen}
                color="inherit"
              >
                {user?.avatar ? (
                  <Avatar 
                    src={user.avatar} 
                    alt={user.username || user.email}
                    sx={{ width: 32, height: 32 }}
                  />
                ) : (
                  <AccountCircle />
                )}
              </IconButton>
              
              <Menu
                id="user-menu"
                anchorEl={anchorEl}
                open={Boolean(anchorEl)}
                onClose={handleMenuClose}
                anchorOrigin={{
                  vertical: 'bottom',
                  horizontal: 'right',
                }}
                transformOrigin={{
                  vertical: 'top',
                  horizontal: 'right',
                }}
              >
                <MenuItem disabled>
                  <Typography variant="body2" color="text.secondary">
                    {user?.username || user?.email || '用户'}
                  </Typography>
                </MenuItem>
                <Divider />
                <MenuItem onClick={handleProfile}>
                  <AccountCircle sx={{ mr: 1 }} />
                  个人资料
                </MenuItem>

                {isAdmin && (
                  <>
                    <MenuItem onClick={handleContentManagement}>
                      <AdminPanelSettings sx={{ mr: 1 }} />
                      内容管理
                    </MenuItem>
                    <MenuItem onClick={handleRecommendationManagement}>
                      <Assessment sx={{ mr: 1 }} />
                      推荐管理
                    </MenuItem>
                  </>
                )}

                {/* 审核管理菜单项 - 仅超级管理员可见 */}
                {isSuperAdmin && (
                  <MenuItem onClick={handleAdminReview}>
                    <Gavel sx={{ mr: 1 }} />
                    审核管理
                  </MenuItem>
                )}
                
                <Divider />
                <MenuItem onClick={handleLogout}>
                  <ExitToApp sx={{ mr: 1 }} />
                  退出登录
                </MenuItem>
              </Menu>
            </>
          ) : (
            // 未登录状态
            <>
              <Button color="inherit" component={Link} to="/auth/login">
                登录
              </Button>
              <Button color="inherit" component={Link} to="/auth/register">
                注册
              </Button>
            </>
          )}
        </Box>
      </Toolbar>
    </AppBar>
  );
};

export default Header; 